package cn.czg.cms.service;

import cn.czg.cms.entity.Message;
import cn.czg.cms.entity.User;
import cn.czg.cms.entity.dto.MessageDTO;
import cn.czg.cms.entity.vo.MessageConversationVO;
import cn.czg.cms.mapper.MessageMapper;
import cn.czg.cms.mapper.UserMapper;
import cn.czg.cms.netty.NettyChannelManager;
import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class MessageService {

    private UserMapper userMapper;
    private final NettyChannelManager nettyChannelManager;

    private final MessageMapper messageMapper;

    public MessageService(UserMapper userMapper, NettyChannelManager nettyChannelManager, MessageMapper messageMapper) {
        this.userMapper = userMapper;
        this.nettyChannelManager = nettyChannelManager;
        this.messageMapper = messageMapper;
    }

    public void sendMessage(Long senderId, MessageDTO dto) {
        Message msg = new Message();
        msg.setSenderId(senderId);
        msg.setReceiverId(dto.getToUserId());
        msg.setType("chat");
        msg.setContent(dto.getContent());
        msg.setConversationId(generateConversationId(senderId, dto.getToUserId()));
        msg.setSendTime(LocalDateTime.now());

        messageMapper.insert(msg);
        log.info("消息入库成功 {}", JSONUtil.toJsonStr(msg));

        // 在线推送
        Channel channel = nettyChannelManager.getChannel(dto.getToUserId());
        if (channel != null) {
            log.info("推送给用户 {}：{}", dto.getToUserId(), JSONUtil.toJsonStr(msg));
            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(msg)));
        }
    }

    private String generateConversationId(Long a, Long b) {
        return a < b ? a + "_" + b : b + "_" + a;
    }


    public List<Message> getChatHistory(Long userId, Long peerId, int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return messageMapper.selectChatHistory(userId, peerId, offset, pageSize);
    }

    public List<MessageConversationVO> getConversations(Long myId) {
        List<Message> lastMessages = messageMapper.selectLastMessages(myId);
        List<MessageConversationVO> result = new ArrayList<>();

        for (Message msg : lastMessages) {
            Long otherUserId = msg.getSenderId().equals(myId) ? msg.getReceiverId() : msg.getSenderId();
            User user = userMapper.selectById(otherUserId);

            Integer unreadCount = messageMapper.countUnread(myId, otherUserId);

            MessageConversationVO vo = new MessageConversationVO();
            vo.setUserId(user.getId());
            vo.setNickname(user.getNickname());
            vo.setAvatar(user.getAvatar());
            vo.setLastMessage(msg);
            vo.setUnreadCount(unreadCount);

            result.add(vo);
        }

        return result;
    }
}
